from datetime import datetime

class Order:
    def __init__(self, order_id=None, user_id=None, order_status=None, order_time=None, total_amount=None):
        self.order_id = order_id
        self.user_id = user_id
        self.order_status = order_status  # '待支付', '已支付', '配送中', '已完成'
        self.order_time = order_time if order_time else datetime.now()
        self.total_amount = total_amount
    
    def to_dict(self):
        order_time_str = self.order_time.strftime('%Y-%m-%d %H:%M:%S') if isinstance(self.order_time, datetime) else self.order_time
        return {
            'order_id': self.order_id,
            'user_id': self.user_id,
            'order_status': self.order_status,
            'order_time': order_time_str,
            'total_amount': self.total_amount
        }
    
    @classmethod
    def from_dict(cls, data):
        order_time = data.get('order_time')
        if isinstance(order_time, str):
            try:
                order_time = datetime.strptime(order_time, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                order_time = None
        
        return cls(
            order_id=data.get('order_id'),
            user_id=data.get('user_id'),
            order_status=data.get('order_status'),
            order_time=order_time,
            total_amount=data.get('total_amount')
        )